/*
 * @Author: 大辉 dbstt@qq.com
 * @Date: 2023-05-05 10:50:03
 * @LastEditors: 大辉 dbstt@qq.com
 * @LastEditTime: 2023-05-17 19:45:14
 * @FilePath: /intelligentQuery/src/redux/query.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createSlice } from '@reduxjs/toolkit';
import update from "immutability-helper";
import { message } from "antd";

export const Query = createSlice({
  name: 'Query',
  initialState: {
    operatorMap: {},
    conditionList: []
  },
  reducers: {
    setCondition(state, { payload }) {
      for (let k in state.conditionList) {
        if (state.conditionList[k].id === payload.id) {
          // state.conditionList.splice(k, 1);
          state.conditionList[k][payload.key] = payload.keyValue
          break;
        }
      }
    },
    addCondition: (state, { payload }) => {
      let bool = true;
      for (let k of state.conditionList) {
        if (k.id === payload.id) {
          bool = false;
          message.warning(`${k.cnName} 已存在，请勿重复添加`);
          break;
        }
      }

      bool && state.conditionList.push(payload);
    },
    delCondition: (state, valObj) => {
      for (let k in state.conditionList) {
        if (state.conditionList[k].id === valObj.payload) {
          state.conditionList.splice(k, 1);
          break;
        }
      }
    },
    moveCondition: (state, { payload }) => {
      state.conditionList = update(state.conditionList, {
        $splice: [
          [payload.dragIndex, 1],
          [payload.hoverIndex, 0, state.conditionList[payload.dragIndex]],
        ],
      });
    },
    clearCondition: (state) => {
      state.conditionList = [];
    },
    loadCondition(state, valobj) {
      state.conditionList = valobj.payload;
    },
    setOperatorMap(state, valObj) {
      state.operatorMap = valObj.payload;
    },


    // increment: (state) => {
    //   // Redux Toolkit 允许我们在 reducers 中编写 mutating 逻辑。
    //   // 它实际上并没有 mutate state 因为它使用了 Immer 库，
    //   // 它检测到草稿 state 的变化并产生一个全新的基于这些更改的不可变 state
    //   state.value += 1;
    // }
  }
});

// 为每个 case reducer 函数生成 Action creators
export const { setCondition, clearCondition, delCondition, addCondition, setOperatorMap, loadCondition, moveCondition } = Query.actions;

export default Query.reducer;